﻿using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace XCI.App
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            DaemonCore(args);
        }

        private static void DaemonCore(string[] args)
        {
            if (args == null || args.Length == 0) return;
            if (args[0] == "restart")//重启应用
            {
                string processIdStr = args[1]; //当前运行程序进程Id
                if (int.TryParse(processIdStr, out var processId))
                {
                    try
                    {
                        Process p = Process.GetProcessById(processId);
                        if (!p.HasExited)
                        {
                            p.Kill();
                        }
                    }
                    catch (Exception e)
                    {
                        Trace.TraceError(e.Message);
                    }
                }
                try
                {
                    string starupPath = args[2];   //启动文件路径
                    string starupParams = string.Empty;
                    if (args.Length > 3)
                    {
                        starupParams = args[3]; //启动参数
                    }
                    Process.Start(starupPath, starupParams);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    Environment.Exit(0);
                }
            }
            else if (args[0] == "kill")
            {
                string processIdStr = args[1]; //当前运行程序进程Id
                if (int.TryParse(processIdStr, out var processId))
                {
                    try
                    {
                        Process p = Process.GetProcessById(processId);
                        if (!p.HasExited)
                        {
                            p.Kill();
                        }
                    }
                    catch (Exception e)
                    {
                        Trace.TraceError(e.Message);
                    }
                }
            }
        }
    }
}
